// ************************************************************
// Copyright © 2021
// File Name: book.go
// Author:
// Email:
// Created: 2021-12-27 10:06:02 (CST)
// Last Update:
//          By:
// Description:
// ************************************************************
package service

import (
	"bookstore/api"
	"bookstore/internal/biz"
	"context"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type BookInfo struct {
	api.UnimplementedBookInfoServer
	biz *biz.BookBiz
}

func NewBookInfo(biz *biz.BookBiz) *BookInfo {
	return &BookInfo{
		biz: biz,
	}
}

func (b BookInfo) AddBook(ctx context.Context, request *api.Book) (*api.BookId, error) {
	nbook := &biz.BookDO{}
	nbook.Id = request.Id
	nbook.Name = request.Name
	nbook.Authors = request.Authors
	nbook.Press = request.Press
	err := b.biz.Add(nbook)
	if err != nil {
		return nil, status.Error(codes.Code(1), "Exists")
	}
	return &api.BookId{
		Id: nbook.Id,
	}, nil
}

func (b BookInfo) GetBook(ctx context.Context, request *api.BookId) (*api.Book, error) {
	book, err := b.biz.Get(request.Id)
	if err != nil {
		return nil, status.Error(codes.Code(1), "Not found")
	}
	return &api.Book{
		Id:      book.Id,
		Name:    book.Name,
		Authors: book.Authors,
		Press:   book.Press,
	}, nil

}
